﻿using OpenCvSharp;
using OpenCvSharp.Extensions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Point = OpenCvSharp.Point;
using Size = OpenCvSharp.Size;
using OpenCvSharp.Extensions;
using Common.plate.common;

namespace Common.plate.plateRecognizer
{
 
    /// <summary>
    /// 图片处理工具类
    /// </summary>
    public class ImageProcessor 
    {
        public static Mat ProcessImage(string imagePath, string outputPath)
        {
            string imagePatht = null;
            var imageFiles = Directory.GetFiles(imagePath, "*.jpg");
            string? outputDir = null;
            outputDir = Path.Combine(outputPath, "1.jpg");

            using (var capture = imagePath == null ? new VideoCapture(0) : new VideoCapture(imagePath))
            {
                if (!capture.IsOpened())
                {
                    Console.WriteLine("错误：无法打开视频源");
                    return null;
                }
                // 1. 读取图像
                Mat img = new Mat();
                if (!capture.Read(img))
                {
                    return null;
                }                
                // 初始化车牌识别器
                var plateRec = new PlateRecognizer();
                // 识别车牌
                var plateObjs = plateRec.RecognizePlate(img);
                // 更新全局车牌变量（仅保留高置信度结果）
                GlobalData.Plate = plateObjs.Any(p => p.ScoreText > 0.8f)
                    ? plateObjs.First(p => p.ScoreText > 0.8f).Text
                    : null;
                // 绘制识别结果（边界框和文字）
                ResultVisualizer resultVisualizer = new ResultVisualizer();
                foreach (var obj in plateObjs.Where(p => p.ScoreText > 0.8f))
                {
                    resultVisualizer.DrawDetectionWithChinese1(img, obj);
                }

                Cv2.ImShow("车牌识别", img);
                Cv2.WaitKey(1000);
                Console.WriteLine($"车牌号：{GlobalData.Plate}");

                if (!string.IsNullOrEmpty(outputDir))
                {
                    Cv2.ImWrite(outputDir, img);
                    Console.WriteLine($"处理完成，结果已保存到 {outputPath}");
                }
                capture.Release();
                return img;
                
            }           
        }      
    }
}
